import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { Button, Checkbox, Dropdown, Tooltip } from 'antd';
import { QuestionCircleOutlined, PlusOutlined } from '#/utils/antdIcons.js';
import styles from './index.less';

/**
 * @param {array} 例: ['时点']
 * @param {array} 例：['时点', '序列']
 * @param {function} onChange 改变聚合参数
 * @param {function} onPoly 点击聚合
 */
export default ({
  loading = false,
  value = [],
  options = [],
  onChange = () => {},
  onPoly = () => {},
  useEdit = true,
  title,
}) => {
  const [checkMap, setCheckMap] = useState({});
  const [diffs, setDiff] = useState([]);
  const [start, setStart] = useState(null);

  useEffect(() => {
    const diffs = _.difference(options, value);
    setDiff(diffs);
  }, [JSON.stringify(value)]);

  /** methods */
  // 排序
  const onDragStart = (i) => {
    if (typeof start === 'number') return;
    setStart(i);
  };
  const onDragEnter = (i) => {
    if (i === start) return;
    setStart(i);
    const temp = _.cloneDeep(value);
    [temp[start], temp[i]] = [temp[i], temp[start]];
    onChange?.(temp);
  };
  const onDragOver = (e) => {
    e.preventDefault();
  };
  const onDragLeave = (e) => {
    e.preventDefault();
  };
  const onDragEnd = (e) => {
    e.preventDefault();
    setStart(null);
  };

  // 删除
  const onDelete = (i) => {
    const temp = _.cloneDeep(value);
    temp.splice(i, 1);
    onChange?.(temp);
  };

  // 添加
  const onChangeCheck = (e, label) => {
    setCheckMap({
      ...checkMap,
      [label]: e.target.checked,
    });
  };
  const onVisibleChange = (open) => {
    let temp = [...value];
    for (const key in checkMap) {
      if (checkMap[key]) temp.push(key);
    }
    if (!open) {
      setCheckMap({});
      onChange?.(temp);
    }
  };

  /** renders */
  return (
    <div className={styles.flexBetween}>
      <div className={styles.flex}>
        <div className={styles.title}>
          {title ? (
            title
          ) : (
            <>
              聚合维度选择
              <Tooltip
                title={`功能支持的数据聚合维度包括${options
                  .map((x) => `“${x}”`)
                  .join('、')}，您可通过增减维度数量、调整维度顺序来控制数据聚合，获得想要的效果。`}
              >
                <QuestionCircleOutlined style={{ color: '#FD4F43', marginLeft: '4px' }} />
              </Tooltip>
            </>
          )}
        </div>

        {/* 拖拽 */}
        {value.map((label, i) => (
          <div
            key={label}
            className={styles.btnDrag}
            draggable
            onDragStart={() => onDragStart(i)}
            onDragEnter={() => onDragEnter(i)}
            onDragOver={(e) => onDragOver(e)}
            onDragLeave={(e) => onDragLeave(e)}
            onDragEnd={(e) => onDragEnd(e)}
          >
            <Button
              style={{ minWidth: 68, hegiht: 32 }}
              className={`${styles.btn} ${start === i ? styles.drag : ''}`}
            >
              {label}
            </Button>
            {value.length > 1 && useEdit && (
              <div className={styles.del} onClick={() => onDelete(i)} />
            )}
          </div>
        ))}

        {useEdit && (
          <Dropdown
            overlay={
              <div className={styles.dropdown}>
                {diffs.map((label) => (
                  <div key={label} onClick={(e) => e.stopPropagation()}>
                    <Checkbox checked={checkMap?.[label]} onChange={(e) => onChangeCheck(e, label)}>
                      {label}
                    </Checkbox>
                  </div>
                ))}
              </div>
            }
            onVisibleChange={onVisibleChange}
            disabled={!diffs.length}
            placement="bottomLeft"
            trigger={['click']}
          >
            <Button
              style={{ width: 32, hegiht: 32 }}
              className={styles.btn}
              disabled={!diffs.length}
              icon={<PlusOutlined />}
            />
          </Dropdown>
        )}
      </div>

      <div>
        <Button style={{ width: 98, height: 32 }} type="primary" onClick={onPoly} loading={loading}>
          聚合
        </Button>
      </div>
    </div>
  );
};
